package compiler;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import language.LArray;
import language.LType;

public class NamedFunction extends Named implements Func {

    final char variable;

    NamedFunction(List list, Map<String, LType> constants) {
        super(list, constants);
        variable = (Character) list.get(2);
    }

    LType call(LType input) {
        return new Instance(input).next();
    }

    @Override
    public LType accept(LType l, Map<Character, LType> vars) {
        return call(l);
    }

    class Instance extends Named.Instance {

        final LType input;

        private Instance(LType input) {
            this.input = input;
        }

        @Override
        Object of(String s) {
            if (s.charAt(0) == variable) {
                return input;
            }
            if (constants.containsKey(s)) {
                return constants.get(s);
            }
            throw new RuntimeException("Unrecongnized symbol: " + s);
        }

        @Override
        Map<Character, LType> newMap() {
            Map<Character, LType> map = new HashMap();
            map.put(variable, input);
            return map;
        }
    }

    @Override
    public String toString() {
        return call(LArray.of(new Scanner(System.in).nextLine())).toString();
    }
}
